package org.pz.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 打印日志，全局过滤器
 * */
@Component
@Slf4j
public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("全局日志过滤器-------------------开始");

        // 记录请求开始时间
        long startTime = System.currentTimeMillis();

        // 获取请求信息
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String method = request.getMethodValue();
        String query = request.getURI().getQuery();
        String headers = request.getHeaders().toString();

        // 记录请求日志
        log.info("Request => Method: {}, Path: {}, Query: {}, Headers: {}", method, path, query, headers);

        // 继续处理请求，并在响应返回后记录日志
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 获取响应信息
            int status = exchange.getResponse().getStatusCode() != null
                    ? exchange.getResponse().getStatusCode().value()
                    : 500;
            long duration = System.currentTimeMillis() - startTime;

            // 记录响应日志
            log.info("Response => Status: {}, Duration: {}ms", status, duration);


            log.info("全局日志过滤器-------------------结束");
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
